<?php

namespace app\admin\model\hotel;

use app\admin\model\vip\Card;
use think\Model;

/**
 * Hotel
 */
class Hotel extends Model
{
    // 表名
    protected $name = 'hotel';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'hotelCate',
        'VipCard',
    ];


    protected static function onAfterInsert($model): void
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getHotelCateAttr($value, $row): array
    {
        return [
            'name' => \app\admin\model\hotel\Cate::whereIn('id', $row['hotel_cate_ids'])->column('name'),
        ];
    }

    public function getVipCardAttr($value, $row): array
    {
        return [
            'name' => Card::whereIn('id', $row['vip_card_ids'])->column('name'),
        ];
    }

    public function getHotelCateIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setHotelCateIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getBannerAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setBannerAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getHotelDesAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function getTrafficBusAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function getBookNoticeAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function getVipCardIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }


    public function setVipCardIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function member(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Member::class, 'member_id', 'id');
    }
}
